package x.ovo.wechat.bot.http.response;

import lombok.Data;
import x.ovo.wechat.bot.common.enums.LoginMode;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * QRCODE 响应
 *
 * @author ovo, created by 2024/04/21
 */
@Data
public class QRCodeResponse {

    private static final Pattern CHECK_LOGIN_PATTERN = Pattern.compile("window.code=(\\d+)");
    private static final Pattern PROCESS_LOGIN_PATTERN = Pattern.compile("window.redirect_uri=\"(\\S+)\";");

    private LoginMode loginMode;
    private String url;

    /**
     * 根据响应信息创建
     * <p> window.code=xxx;window.redirect_uri="https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage?ticket=xxx&uuid=xxx&lang=xxx&scan=xxx";
     *
     * @param data 数据
     * @return {@link QRCodeResponse}
     */
    public static QRCodeResponse from(String data) {
        QRCodeResponse response = new QRCodeResponse();
        Matcher matcher = CHECK_LOGIN_PATTERN.matcher(data);
        if (matcher.find()) {
            response.setLoginMode(LoginMode.get(Integer.parseInt(matcher.group(1))));
        }
        matcher = PROCESS_LOGIN_PATTERN.matcher(data);
        if (matcher.find()) {
            response.setUrl(matcher.group(1));
        }
        return response;
    }
}
